package com.dotstone.chipism.activity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.CodeInfo;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.PhoneUtil;
import com.dotstone.chipism.util.StringUtil;
import com.dotstone.chipism.util.TimeUtils;
import com.dotstone.chipism.util.ToastShow;
import com.google.gson.Gson;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ForgetPwdActivity extends BaseActivity {
	private View mBlock;
	private LinearLayout mBackL;
	private TextView mTitleTv;
	private Button mSendBtn;
	private EditText mTelEd;
	private EditText mNewEd;
	private EditText mNewEd1;
	private EditText mCheckEd;
	private Button mConfirmBtn;
	private boolean fromLogin = false;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			if (fromLogin) {
				Intent intent = new Intent(ForgetPwdActivity.this,LoginActivity.class);
				startActivity(intent);
				finish();
			} else {
				finish();
			}
			break;
		case R.id.confirm_btn:
			// 判断两次输入的密码是否一致
			checkPwd();
			break;
		case R.id.send_btn:
//			getVerification();
			checkUsed();
			break;
		default:
			break;
		}
	}
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void exit(){
		if (fromLogin) {
			Intent intent = new Intent(ForgetPwdActivity.this,LoginActivity.class);
			startActivity(intent);
			finish();
		} else {
			finish();
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_forget_pwd;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBlock = (View) findViewById(R.id.block);
		mTitleTv = (TextView) findViewById(R.id.title_tv);
		mTitleTv.setText(R.string.changepassword);
		mBackL = (LinearLayout) findViewById(R.id.back_layout);
		mSendBtn = (Button) findViewById(R.id.send_btn);
		mTelEd = (EditText) findViewById(R.id.tel_edit);
		mNewEd = (EditText) findViewById(R.id.pwd_ed1);
		mNewEd1 = (EditText) findViewById(R.id.pwd_ed2);
		mConfirmBtn = (Button) findViewById(R.id.confirm_btn);
		mCheckEd = (EditText) findViewById(R.id.check_edit);
		mBackL.setOnClickListener(this);
		mConfirmBtn.setOnClickListener(this);
		mSendBtn.setOnClickListener(this);
		fromLogin = getIntent().getBooleanExtra("fromLogin", false);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			int resourceId = getResources().getIdentifier("status_bar_height",
					"dimen", "android");
			int statusBarHeight = getResources().getDimensionPixelSize(
					resourceId);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
			mBlock.setLayoutParams(params);
		}
		mTelEd.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mTelEd.setHint("");
				} else {
					if (mTelEd.getText().toString().length() == 0) {
						mTelEd.setHint(getString(R.string.phone_num));
					}
				}
			}
		});
		mNewEd.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mNewEd.setHint("");
				} else {
					if (mNewEd.getText().toString().length() == 0) {
						mNewEd.setHint(getString(R.string.new_pwd));
					}
				}
			}
		});
		mNewEd1.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mNewEd1.setHint("");
				} else {
					if (mNewEd1.getText().toString().length() == 0) {
						mNewEd1.setHint(getString(R.string.pwd1));
					}
				}
			}
		});
		mCheckEd.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mCheckEd.setHint("");
				} else {
					if (mCheckEd.getText().toString().length() == 0) {
						mCheckEd.setHint(getString(R.string.check));
					}
				}
			}
		});
	}
	
	protected void checkUsed() {
		// 先正则判断 再发送
		if (NetUtil.isNetworkAvailable(this)) {
			String telNumber = mTelEd.getText().toString().trim();
			if (TextUtils.isEmpty(telNumber)) {
				ToastShow.Show(getApplicationContext(),
						getString(R.string.phone_not_null));
				return;
			}

			if (!PhoneUtil.isMobileNO(telNumber)) {
				ToastShow.Show(getApplicationContext(),
						getString(R.string.phone_not_right));
				return;
			}
			CodeInfo codeInfo = new CodeInfo();
			codeInfo.setKey("10000");
			codeInfo.setMobile(telNumber);
			codeInfo.setRequestTime(String.valueOf(System.currentTimeMillis()));
			Gson gson = new Gson();
			RequestParams params = new RequestParams(HttpURL.CHECK_PHONE);
			params.setBodyContent(gson.toJson(codeInfo));
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("Tag", "senCode=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						int value = jsonObject.optInt("resultCode");
						if (value == 1) {
							boolean exist = jsonObject.getBoolean("data");
							if (exist) {
//								getVerification();
								ToastShow
								.Show(getApplicationContext(),
										"该号码不存在或尚未注册！");
							} else {
								getVerification();
							}
						} else if (value == 103) {
							ToastShow.Show(getApplicationContext(),
									getString(R.string.number_has_rogistered));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {
					Log.e("Tag", "onError" + ex.getMessage());
				}

				@Override
				public void onCancelled(CancelledException cex) {
					Log.e("Tag", "onCancelled");
				}

				@Override
				public void onFinished() {
					Log.e("Tag", "onFinished");
				}
			});
		} else {
			Toast toast = Toast.makeText(getApplicationContext(),
					R.string.nonetwork, Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	private void getVerification() {
		if (NetUtil.isNetworkAvailable(this)) {
			String phone = mTelEd.getText().toString().trim();
			if (TextUtils.isEmpty(phone)) {
				Toast toast = Toast.makeText(getApplicationContext(),
						R.string.phone_not_null, Toast.LENGTH_SHORT);
				toast.show();
				return;
			}
			// TODO 判断是不是当前的登录号码

			TimeUtils timeUtils = new TimeUtils(mSendBtn, mSendBtn.getText()
					.toString());
			timeUtils.RunTimer();
			RequestParams params = new RequestParams(HttpURL.REG_CODE_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("codeType", "2");
				obj.put("key", "10000");
				obj.put("mobile", phone);
				obj.put("requestTime", "" + System.currentTimeMillis());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("test", "senCode=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						int value = jsonObject.optInt("value");
						if (value == 100) {
							Toast toast = Toast.makeText(
									getApplicationContext(),
									R.string.send_code_success,
									Toast.LENGTH_SHORT);
							toast.show();
						} else if (value == 103) {
							Toast toast = Toast.makeText(
									getApplicationContext(),
									R.string.phone_has_register,
									Toast.LENGTH_SHORT);
							toast.show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {

				}

				@Override
				public void onCancelled(CancelledException cex) {
				}

				@Override
				public void onFinished() {
				}
			});
		} else {
			Toast toast = Toast.makeText(getApplicationContext(),
					R.string.nonetwork, Toast.LENGTH_SHORT);
			toast.show();
		}

	}

	private void checkPwd() {
		final String pwd = mNewEd.getText().toString().trim();
		String pwd2 = mNewEd1.getText().toString();
		if (pwd.equals(pwd2)) {
			if (NetUtil.isNetworkAvailable(this)) {
				final String phone = mTelEd.getText().toString().trim();
				if (TextUtils.isEmpty(phone)) {
					Toast toast = Toast.makeText(getApplicationContext(),
							R.string.phone_not_null, Toast.LENGTH_SHORT);
					toast.show();
					return;
				}

				if (!PhoneUtil.isMobileNO(phone)) {
					Toast toast = Toast.makeText(getApplicationContext(),
							R.string.phone_not_right, Toast.LENGTH_SHORT);
					toast.show();
					return;
				}

				String code = mCheckEd.getText().toString().trim();
				if (TextUtils.isEmpty(code)) {
					Toast toast = Toast.makeText(getApplicationContext(),
							R.string.send_code_not_null, Toast.LENGTH_SHORT);
					toast.show();
					return;
				}
				if (TextUtils.isEmpty(pwd)) {
					Toast toast = Toast.makeText(getApplicationContext(),
							R.string.pwd_not_null, Toast.LENGTH_SHORT);
					toast.show();
					return;
				}

				if (pwd.length() < 6 || pwd.length() > 12) {
					Toast toast = Toast.makeText(getApplicationContext(),
							R.string.pwd_length_not_right, Toast.LENGTH_SHORT);
					toast.show();
					return;
				}

				if (StringUtil.isNumeric(pwd)) {
					Toast toast = Toast.makeText(getApplicationContext(),
							R.string.pwd_not_all_num, Toast.LENGTH_SHORT);
					toast.show();
					return;
				}

				if (StringUtil.isChar(pwd)) {
					Toast toast = Toast.makeText(getApplicationContext(),
							R.string.pwd_not_all_letter, Toast.LENGTH_SHORT);
					toast.show();
					return;
				}

				if (StringUtil.isConSpeCharacters(pwd)) {
					Toast toast = Toast.makeText(getApplicationContext(),
							R.string.pwd_not_all_character, Toast.LENGTH_SHORT);
					toast.show();
					return;
				}
//				ToastShow.Show(getApplicationContext(), HttpURL.UPDATE_PWD_URL);
				if (NetUtil.isNetworkAvailable(this)) {
					RequestParams params = new RequestParams(
							HttpURL.UPDATE_PWD_URL);
					params.setAsJsonContent(true);
					JSONObject obj = new JSONObject();
					try {
						obj.put("checkCode", code);
						obj.put("key", "10000");
						obj.put("mobile", phone);
						obj.put("password", pwd);
						obj.put("requestTime", System.currentTimeMillis() + "");
						Log.d("test", "forget obj = " + obj.toString());
					} catch (JSONException e1) {
						e1.printStackTrace();
					}
					params.setBodyContent(obj.toString());
					x.http().post(params,
							new Callback.CommonCallback<String>() {
								@Override
								public void onSuccess(String result) {
									Log.e("test", "forget =" + result);
									try {
										JSONObject jsonObject = new JSONObject(
												result);
										String resultCode = jsonObject
												.getString("resultCode");
										if (resultCode.equals("1")) {
											ToastShow
													.Show(getApplicationContext(),
															getString(R.string.change_success));
											Intent intent = new Intent(
													ForgetPwdActivity.this,
													LoginActivity.class);
											startActivity(intent);
											finish();
										} else {
											String errorMsg = jsonObject
													.getString("errorMsg");
											ToastShow.Show(
													getApplicationContext(),
													errorMsg);
										}
									} catch (JSONException e) {
										e.printStackTrace();
									}
								}

								@Override
								public void onError(Throwable ex,
										boolean isOnCallback) {

								}

								@Override
								public void onCancelled(CancelledException cex) {
								}

								@Override
								public void onFinished() {
								}
							});
				} else {
					Toast toast = Toast.makeText(getApplicationContext(),
							R.string.nonetwork, Toast.LENGTH_SHORT);
					toast.show();
				}
			} else {
				Toast toast = Toast.makeText(getApplicationContext(),
						R.string.nonetwork, Toast.LENGTH_SHORT);
				toast.show();
			}
		} else {
			ToastShow.Show(getApplicationContext(),
					getString(R.string.password_no_agree));
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

}
